package com.jack.leetcode.eachProblem08;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class 恢复二叉搜索树 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private class Node {
        int val;
        TreeNode root;

        public Node(int val, TreeNode root) {
            this.val = val;
            this.root = root;
        }
    }

    private List<Node> list = new ArrayList<>();

    public void recoverTree(TreeNode root) {
        if (root == null) {
            return;
        }
        middleSearch(root);
        int position1 = -1;
        int position2 = -1;
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i).val > list.get(i + 1).val) {
                if (position1 == -1) {
                    position1 = i;
                    position2 = i + 1;
                } else {
                    position2 = i + 1;
                    break;
                }
            }
        }
        System.out.println(position1);
        System.out.println(position2);
        int tmp = list.get(position1).val;
        list.get(position1).val = list.get(position2).val;
        list.get(position2).val = tmp;
    }

    private void middleSearch(TreeNode root) {
        if (root == null) {
            return;
        }
        middleSearch(root.left);
        list.add(new Node(root.val, root));
        middleSearch(root.right);
    }
}
